package com.ruge.core.tool;

import org.springframework.http.HttpHeaders;
import org.springframework.web.server.ServerWebExchange;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * description: HttpServletRequest 工具类
 * create time at 2022/6/6 11:32
 *
 * @author alice.ruge
 * @since 0.0.3
 */

public class RequestTool {
    public RequestTool() {
    }

    public static String getBodyString(HttpServletRequest request) throws IOException {
        try {
            ServletInputStream inputStream = request.getInputStream();
            StringBuilder content = new StringBuilder();
            byte[] b = new byte[1024];
            boolean var4 = true;

            int lens;
            while ((lens = inputStream.read(b)) > 0) {
                content.append(new String(b, 0, lens));
            }

            return content.toString();
        } catch (Throwable var5) {
            throw var5;
        }
    }

    public static Map<String, String> getParameterMap(HttpServletRequest request) {
        Map<String, String> map = new HashMap<>(16);
        Enumeration<String> paramNames = request.getParameterNames();
        return enumToMap(request, map, paramNames);
    }

    public static Map<String, String> getHeaderMap(HttpServletRequest request) {
        Map<String, String> map = new HashMap<>(16);
        Enumeration paramNames = request.getHeaderNames();
        while (paramNames.hasMoreElements()) {
            String paramName = (String) paramNames.nextElement();
            String paramValue = request.getHeader(paramName);
            map.put(paramName, paramValue);
        }
        return map;
    }

    public static Map<String, List<String>> getHeaderMap(ServerWebExchange exchange) {
        HttpHeaders headers = exchange.getRequest().getHeaders();
        Map<String, List<String>> map = new HashMap<>(16);
        for (Map.Entry<String, List<String>> entry : headers.entrySet()) {
            map.put(entry.getKey(), entry.getValue());
        }
        return map;
    }

    private static Map<String, String> enumToMap(HttpServletRequest request, Map<String, String> map, Enumeration<String> paramNames) {
        while (paramNames.hasMoreElements()) {
            String paramName = paramNames.nextElement();
            String[] paramValues = request.getParameterValues(paramName);
            if (null != paramValues && paramValues.length == 1) {
                String paramValue = paramValues[0];
                if (paramValue.length() != 0) {
                    map.put(paramName, paramValue);
                }
            }
        }

        return map;
    }
}
